"""
日志管理模块 - 统一的日志配置和管理
"""

import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler


class LoggerManager:
    """日志管理器"""
    
    def __init__(self, log_dir: str = None):
        """
        初始化日志管理器
        Args:
            log_dir: 日志目录，为空则使用默认目录
        """
        if log_dir is None:
            log_dir = os.path.join(os.path.dirname(__file__), '..', 'logs')
        
        self.log_dir = log_dir
        os.makedirs(self.log_dir, exist_ok=True)
        
        # 配置根日志记录器
        self.setup_root_logger()
    
    def setup_root_logger(self):
        """配置根日志记录器"""
        # 创建根日志记录器
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.INFO)
        
        # 清除已有的处理器
        for handler in root_logger.handlers[:]:
            root_logger.removeHandler(handler)
        
        # 创建格式器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        root_logger.addHandler(console_handler)
        
        # 文件处理器 - 主日志文件(覆盖写入)
        main_log_file = os.path.join(self.log_dir, 'app.log')
        file_handler = logging.FileHandler(main_log_file, mode='w', encoding='utf-8')
        file_handler.setLevel(logging.INFO)
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)
        
        # 错误日志文件处理器(轮转)
        error_log_file = os.path.join(self.log_dir, 'error.log')
        error_handler = RotatingFileHandler(
            error_log_file, 
            maxBytes=10*1024*1024,  # 10MB
            backupCount=3,
            encoding='utf-8'
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(formatter)
        root_logger.addHandler(error_handler)
        
        logging.info("日志系统初始化完成")
    
    def get_logger(self, name: str) -> logging.Logger:
        """
        获取指定名称的日志记录器
        Args:
            name: 日志记录器名称
        Returns:
            日志记录器实例
        """
        return logging.getLogger(name)
    
    def create_module_logger(self, module_name: str, log_file: str = None) -> logging.Logger:
        """
        为特定模块创建专用日志记录器
        Args:
            module_name: 模块名称
            log_file: 专用日志文件名
        Returns:
            模块日志记录器
        """
        logger = logging.getLogger(module_name)
        
        # 如果指定了专用日志文件，添加文件处理器
        if log_file:
            log_path = os.path.join(self.log_dir, log_file)
            file_handler = logging.FileHandler(log_path, mode='w', encoding='utf-8')
            file_handler.setLevel(logging.INFO)
            
            formatter = logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)
        
        return logger
    
    def log_operation(self, operation: str, details: str, status: str = "success"):
        """
        记录操作日志
        Args:
            operation: 操作类型
            details: 操作详情
            status: 操作状态
        """
        logger = logging.getLogger("operation")
        
        if status == "success":
            logger.info(f"✅ {operation}: {details}")
        elif status == "warning":
            logger.warning(f"⚠️ {operation}: {details}")
        elif status == "error":
            logger.error(f"❌ {operation}: {details}")
        else:
            logger.info(f"{operation}: {details}")
    
    def log_system_event(self, event: str, details: str):
        """记录系统事件"""
        logger = logging.getLogger("system")
        logger.info(f"🔧 {event}: {details}")
    
    def log_trading_event(self, event: str, details: str, status: str = "info"):
        """记录交易事件"""
        logger = logging.getLogger("trading")
        
        if status == "success":
            logger.info(f"💰 {event}: {details}")
        elif status == "error":
            logger.error(f"💸 {event}: {details}")
        else:
            logger.info(f"📊 {event}: {details}")
    
    def log_ocr_event(self, event: str, details: str, status: str = "info"):
        """记录OCR事件"""
        logger = logging.getLogger("ocr")
        
        if status == "success":
            logger.info(f"👁️ {event}: {details}")
        elif status == "error":
            logger.error(f"❌ {event}: {details}")
        else:
            logger.info(f"🔍 {event}: {details}")
    
    def get_log_content(self, log_file: str = "app.log", lines: int = 100) -> str:
        """
        获取日志文件内容
        Args:
            log_file: 日志文件名
            lines: 读取行数
        Returns:
            日志内容
        """
        try:
            log_path = os.path.join(self.log_dir, log_file)
            if not os.path.exists(log_path):
                return f"日志文件不存在: {log_file}"
            
            with open(log_path, 'r', encoding='utf-8') as f:
                content_lines = f.readlines()
                
                # 返回最后N行
                if lines > 0 and len(content_lines) > lines:
                    content_lines = content_lines[-lines:]
                
                return ''.join(content_lines)
                
        except Exception as e:
            return f"读取日志文件失败: {e}"
    
    def clear_logs(self):
        """清空日志文件"""
        try:
            for filename in os.listdir(self.log_dir):
                if filename.endswith('.log'):
                    log_path = os.path.join(self.log_dir, filename)
                    open(log_path, 'w').close()  # 清空文件
            
            logging.info("日志文件已清空")
            
        except Exception as e:
            logging.error(f"清空日志文件失败: {e}")


# 全局日志管理器实例
logger_manager = LoggerManager()

# 便捷的日志函数
def get_logger(name: str = __name__) -> logging.Logger:
    """获取日志记录器"""
    return logger_manager.get_logger(name)

def log_operation(operation: str, details: str, status: str = "success"):
    """记录操作日志"""
    logger_manager.log_operation(operation, details, status)

def log_system_event(event: str, details: str):
    """记录系统事件"""
    logger_manager.log_system_event(event, details)

def log_trading_event(event: str, details: str, status: str = "info"):
    """记录交易事件"""
    logger_manager.log_trading_event(event, details, status)

def log_ocr_event(event: str, details: str, status: str = "info"):
    """记录OCR事件"""
    logger_manager.log_ocr_event(event, details, status)
